package org.chouy.json;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;

/**
 * @Package: org.chouy.json
 * @ClassName: JsonServlet
 * @Description: java类作用描述
 * @Author: Zhouy
 * @CreateDate: 2017/12/22 下午10:08
 * @UpdateUser: 更新者
 * @UpdateDate: 2017/12/22 下午10:08
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@WebServlet(name = "JsonServlet",urlPatterns = "/Servlet/JsonServ")
public class JsonServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String jsonS=req.getParameter("jsonObj");
        jsonS=URLDecoder.decode(jsonS,"UTF-8");
        System.out.println(jsonS);
        JSONObject jsonObject = new JSONObject(jsonS);

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("主人姓名："+jsonObject.getString("name")+"</br>");
        stringBuffer.append("主人年龄："+jsonObject.getInt("age")+"</br>");

        JSONArray jsonArray = jsonObject.getJSONArray("family");
        stringBuffer.append("成员介绍：</br>");
        Iterator iterator=jsonArray.iterator();
        while (iterator.hasNext()){
            JSONObject object= (JSONObject) iterator.next();
            stringBuffer.append("角色："+object.getString("name")+"---"+"角色年龄："+object.getInt("age")+"---"+"角色性别："+object.getString("sax")+"</br>");
        }
        System.out.println(stringBuffer.toString());
        resp.getWriter().print(stringBuffer.toString());
    }
}
